<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑客户' : '新建客户'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <!-- ========== 核心必填字段（永远可见） ========== -->
      <el-form-item
        label="客户姓名"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入客户姓名"
          clearable
        />
      </el-form-item>

      <el-form-item
        label="电话号码"
        prop="phone"
      >
        <el-input
          v-model="formData.phone"
          placeholder="请输入电话号码"
          maxlength="11"
          clearable
        />
      </el-form-item>

      <!-- ========== 备注字段（增强：AI 实时提取） ========== -->
      <el-form-item label="备注">
        <el-input
          v-model="formData.notes"
          type="textarea"
          :rows="4"
          placeholder="描述客户需求，AI 将自动提取关键信息..."
          @input="handleNotesChange"
        />

        <!-- AI 自动提取提示 -->
        <el-alert
          v-if="aiExtractedFields.length > 0"
          type="success"
          :closable="false"
          style="margin-top: 8px"
        >
          <template #title>
            <span>💡 AI 已自动识别：{{ aiExtractedFields.join('、') }}</span>
          </template>
        </el-alert>

        <!-- AI 智能补全开关 -->
        <div style="margin-top: 8px; display: flex; align-items: center;">
          <el-switch
            v-model="aiAutoFill"
            active-text="AI 智能补全"
            inactive-text="手动填写"
            size="small"
          />
          <el-text
            size="small"
            type="info"
            style="margin-left: 12px"
          >
            AI 将从备注中自动提取需求类型、预算、户型等信息
          </el-text>
        </div>
      </el-form-item>

      <!-- ========== 可选字段（折叠面板） ========== -->
      <el-collapse
        v-model="activeCollapse"
        style="margin-top: 16px"
      >
        <el-collapse-item
          title="📋 更多信息（可选）"
          name="more"
        >
          <el-form-item label="需求类型">
            <el-select
              v-model="formData.demand_type"
              placeholder="请选择需求类型"
              style="width: 100%"
              clearable
            >
              <el-option
                label="整租"
                value="rent_whole"
              />
              <el-option
                label="合租"
                value="rent_share"
              />
              <el-option
                label="短租"
                value="rent_short"
              />
              <el-option
                label="买房"
                value="buy"
              />
              <el-option
                label="卖房"
                value="sell"
              />
            </el-select>
            <el-text
              v-if="aiExtractedData.demand_type"
              size="small"
              type="success"
              style="margin-top: 4px"
            >
              ✓ AI 已识别
            </el-text>
          </el-form-item>

          <el-form-item label="预算范围">
            <el-input
              v-model="formData.budget_range"
              placeholder="如: 5000-8000元/月"
              clearable
            />
            <el-text
              v-if="aiExtractedData.budget_range"
              size="small"
              type="success"
              style="margin-top: 4px"
            >
              ✓ AI 已识别
            </el-text>
          </el-form-item>

          <el-form-item label="来源渠道">
            <el-select
              v-model="formData.source_channel"
              placeholder="自动默认为微信"
              style="width: 100%"
              clearable
            >
              <el-option
                label="微信"
                value="wechat"
              />
              <el-option
                label="电话"
                value="phone"
              />
              <el-option
                label="转介绍"
                value="referral"
              />
              <el-option
                label="其他"
                value="other"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="跟进阶段">
            <el-select
              v-model="formData.stage"
              placeholder="自动默认为新线索"
              style="width: 100%"
              clearable
            >
              <el-option
                label="新线索"
                value="new"
              />
              <el-option
                label="跟进中"
                value="following"
              />
              <el-option
                label="已成交"
                value="closed"
              />
              <el-option
                label="已失效"
                value="lost"
              />
            </el-select>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>

      <!-- ========== AI 标签显示（编辑时） ========== -->
      <el-form-item
        v-if="isEdit && formData.ai_tags"
        label="AI标签"
      >
        <div class="ai-tags-display">
          <el-tag
            v-for="(value, key) in formData.ai_tags"
            :key="key"
            closable
            style="margin: 4px"
            @close="handleRemoveTag(key)"
          >
            {{ key }}: {{ value }}
          </el-tag>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 客户对话框组件 - 优化版
 *
 * 优化内容：
 * 1. 字段精简：仅 2 个必填（姓名、电话）
 * 2. 折叠面板：次要字段隐藏在折叠面板中
 * 3. AI 智能补全：从备注中实时提取关键信息
 * 4. 智能默认值：来源渠道、跟进阶段自动默认
 */
import { ref, reactive, computed, watch } from 'vue'
import { debounce } from 'lodash-es'
import { ElNotification } from 'element-plus'
import { useLeadStore } from '@/stores/lead'
import { useUserStore } from '@/stores/user'
import { leadApi } from '@/api'
import type { FormInstance, FormRules } from 'element-plus'
import type { Lead, LeadCreate, LeadUpdate, DemandType, AITags } from '@/api/types'

// ========== Props & Emits ==========
interface Props {
  modelValue: boolean
  leadData?: Lead | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// ========== Store ==========
const leadStore = useLeadStore()
const userStore = useUserStore()

// ========== 响应式数据 ==========
const visible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

const isEdit = computed(() => !!props.leadData)

const formRef = ref<FormInstance>()
const loading = ref(false)

// 折叠面板状态（默认关闭）
const activeCollapse = ref<string[]>([])

// AI 自动填充开关（默认开启）
const aiAutoFill = ref(true)

// AI 提取的数据
const aiExtractedData = ref<Record<string, unknown>>({})

// AI 提取的字段列表（用于显示提示）
const aiExtractedFields = computed(() => {
  const fields: string[] = []
  const fieldNames: Record<string, string> = {
    budget_range: '预算范围',
    demand_type: '需求类型',
    layout: '户型',
    area_preferences: '区域偏好'
  }

  Object.keys(aiExtractedData.value).forEach(key => {
    if (aiExtractedData.value[key]) {
      fields.push(fieldNames[key] || key)
    }
  })

  return fields
})

const formData = reactive<LeadCreate & { id?: number; ai_tags?: AITags }>({
  name: '',
  phone: '',
  demand_type: 'rent_whole' as DemandType,
  budget_range: '',
  notes: '',
  source_channel: 'wechat', // 智能默认值
  stage: 'new', // 智能默认值
  owner_id: 0,
})

// 表单验证规则（仅 2 个必填）
const rules: FormRules = {
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
}

// ========== 方法 ==========

/**
 * 初始化表单数据
 */
const initFormData = () => {
  if (props.leadData) {
    Object.assign(formData, props.leadData)
  } else {
    Object.assign(formData, {
      name: '',
      phone: '',
      demand_type: 'rent_whole',
      budget_range: '',
      notes: '',
      source_channel: 'wechat',
      stage: 'new',
      ai_tags: undefined,
    })
  }

  // 清空 AI 提取数据
  aiExtractedData.value = {}
}

/**
 * 处理备注输入变化 - AI 实时提取
 */
const handleNotesChange = debounce(async () => {
  if (!aiAutoFill.value || !formData.notes || formData.notes.length < 20) {
    return
  }

  try {
    // 构建已有数据（避免覆盖用户手动输入）
    const existingData: Record<string, unknown> = {}
    if (formData.budget_range) existingData.budget_range = formData.budget_range
    if (formData.demand_type) existingData.demand_type = formData.demand_type

    // 调用 AI 提取 API
    const result = await leadApi.extractFromNotes(formData.notes, existingData)

    if (result.success && result.data) {
      const extracted = result.data
      aiExtractedData.value = extracted

      // 自动填充字段（仅当字段为空时）
      if (extracted.budget_range && !formData.budget_range) {
        formData.budget_range = extracted.budget_range
      }

      if (extracted.demand_type && !formData.demand_type) {
        formData.demand_type = extracted.demand_type as DemandType
      }

      // 显示提示
      if (Object.keys(extracted).length > 0) {
        ElNotification({
          type: 'info',
          title: 'AI 智能补全',
          message: result.message,
          duration: 3000,
        })
      }
    }
  } catch (error) {
    console.error('AI 提取失败', error)
    // 静默失败，不打扰用户
  }
}, 1000) // 1 秒防抖

/**
 * 移除AI标签
 */
const handleRemoveTag = (key: string) => {
  if (formData.ai_tags) {
    delete formData.ai_tags[key]
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    loading.value = true
    try {
      let success = false
      if (isEdit.value && formData.id) {
        // 编辑
        const { id, ...updateData } = formData
        const result = await leadStore.updateLead(id, updateData as LeadUpdate)
        success = !!result
      } else {
        // 新建
        const createData: LeadCreate = {
          name: formData.name,
          phone: formData.phone,
          demand_type: formData.demand_type,
          budget_range: formData.budget_range,
          notes: formData.notes,
          source_channel: formData.source_channel,
          stage: formData.stage,
          owner_id: userStore.userInfo?.id || 0,
        }
        const result = await leadStore.createLead(createData)
        success = !!result
      }

      if (success) {
        emit('success')
      }
    } finally {
      loading.value = false
    }
  })
}

/**
 * 关闭对话框
 */
const handleClose = () => {
  formRef.value?.resetFields()
  aiExtractedData.value = {}
  activeCollapse.value = []
  visible.value = false
}

// ========== 监听 ==========
watch(
  () => props.leadData,
  () => {
    initFormData()
  },
  { immediate: true }
)
</script>

<style scoped>
.ai-tags-display {
  display: flex;
  flex-wrap: wrap;
}

/* 折叠面板优化样式 */
:deep(.el-collapse-item__header) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-collapse-item__content) {
  padding-top: 16px;
}
</style>
